import { BadRequestException, Injectable } from '@nestjs/common';
import { UsersRepository } from '../user/users.repository';
import { CreateUserDto } from '../user/dto/create-user.dto';
import { User } from '../user/entities/user.entity';
import { LoginDto } from '../user/dto/login.dto';
import { wx } from '../../config/config';
import { wxLoginDto } from '../user/dto/wxLogin.dto';
import { lastValueFrom, map, Observable } from 'rxjs';
import { AxiosResponse } from 'axios';
import { JwtPayload } from '../jwt/jwt-payload.interface';

@Injectable()
export class AuthService extends UsersRepository {
  async createUsers(authCredentialsDto: CreateUserDto): Promise<User> {
    return super.createUser(authCredentialsDto);
  }

  async signIns(loginDto: LoginDto): Promise<{ token: string }> {
    return super.signIn(loginDto);
  }
  // 微信登录
  async wxLogin(wxLogin: wxLoginDto): Promise<any> {
    const { code, iv, encryptedData } = wxLogin;
    const url = `https://api.weixin.qq.com/sns/jscode2session?grant_type=${wx.grantType}&appid=${wx.appId}&secret=${wx.secret}&js_code=${code}`;
    // 获取openid和session_key
    const info = await lastValueFrom(this.getWxAuth(url));
    console.log(info);
    // 如果openid不存在则为新用户
    const hasUser = await super.repository.findOneBy({
      openId: info.data.openid,
    });
    if (!hasUser) {
      // 注册插入一条新信息
      const user = this.repository.create({
        openId: info.data.openid,
        username: info.data.nickName,
        account: info.data.nickName,
        avatar: info.data.avatarUrl,
      });
      await this.repository.save(user);
    }
    const { openId } = info.data.openid;
    const token: string = this.jwtService.sign(openId);
    return { token };
  }
  // 微信二维码
  wxQrcode() {
    const APPID = wx.appId;
    const redirectUri = wx.redirectUri;
    return `https://open.weixin.qq.com/connect/qrconnect?appid=${APPID}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect`;
  }
  // 获取openid和session_key
  getWxAuth(url: string): Observable<AxiosResponse> {
    return this.httpService.post(url).pipe(map((response) => response.data));
  }
}
